<?php

class Baidu_service extends MY_Service {

    function __construct() {
        parent::__construct();

        $this->load->model("api_log_model");

        $this->_baidu_api = config_item("baidu_api");

        $this->_apiKey = $this->_baidu_api["apiKey"];
        $this->_secretKey = $this->_baidu_api["secretKey"];
    }

    /*
     * 登录
     */

    public function getToken($is_force = 0) {

        $token = $this->getFileToken();
        if (empty($token) || $is_force == 1) {
            $data = [];
            $url_add = "?grant_type=client_credentials&client_id=" . $this->_apiKey . "&client_secret=" . $this->_secretKey;
            $rs = $this->postApi($data, '得到access_token', $this->_baidu_api["get_access_token_url"] . $url_add, 0, 0, "get");
            if (isset($rs['status_code']) && $rs['status_code'] == 1) {
                $data = $rs["data"];
                $token = $data['access_token'];
                $this->putFileToken($token);
            }
        }
        return $token;
    }

    /*
     * 
     */

    public function getCaptchaVal($image_url, $is_force = 0) {

        $str = "";
        $data = "url=" . urlencode($image_url);

        $result = $this->postApi($data, '得到getCaptchaVal', $this->_baidu_api["ocr_url"], 1, 0, "post");
        if ($result["status_code"] == 1) {
            $str = $result["data"]["words_result"][0]["words"];
            if (strlen($str) != 4) {
                if ($is_force == 0) {
                    $this->getCaptchaVal($image_url, 1);
                }
            }
        }
        return $str;
    }

    /**
     * 
     */
    public function postApi($params, $item, $url, $token = true, $is_force_get_token = 0, $method = "post") {

        $request_data = [
            "url" => $url,
            "params" => $params,
        ];

        $header = ['Content-Type:application/x-www-form-urlencoded'];
        if ($token) {
            $url .= "?access_token=" . $this->getToken($is_force_get_token);
        }

        $rs = $this->post($url, $params, $header, $method);
        //增加日志
        //file_put_contents(dirname(__FILE__) . "/../../upfile/redis/" . date("Y-m-d H:i:s") . "-" . uniqid() . ".txt", "");
        //申报类接口

        $status_code = 0;
        $msg = "失败";
        $data = [];
        $return_code = "";
        $return_msg = "";

        if ($rs["code"] == 200) {
            $sys_data = jsonDecode($rs["data"]);
            if (is_array($sys_data) && !empty($sys_data)) {
                if (!$token) {
                    if (!empty($sys_data["access_token"])) {
                        $status_code = 1;
                        $msg = "";
                    } else {
                        print_r($sys_data);
                        echo time();
                        $msg = $sys_data["error_description"] . "(" . $sys_data["error"] . ")";
                        $return_code = $sys_data["error"];
                        $retrun_msg = $sys_data["error_description"];
                    }
                } else {
                    if (!isset($sys_data["error_code"])) {
                        $status_code = 1;
                        $msg = "";
                    } else {
                        $msg = $sys_data["error_msg"] . "(" . $sys_data["error_code"] . ")";
                        $return_code = $sys_data["error_code"];
                        $retrun_msg = $sys_data["error_msg"];
                    }
                }
                $data = $sys_data;
            } else {
                $msg = "返回数据格式有误(" . addslashes(htmlspecialchars($rs["data"])) . ")";
            }
        } else {
            $msg = "接口请求失败(" . $rs["data"] . ")";
        }

        $this->api_log_model->addLog(1, "百度->" . $item, $request_data, $rs);

        log_message('error', "百度->" . $item . "(返回数据)=>" . jsonEncode($rs));

        if ($return_code == 110 && $is_force_get_token == 0) {//当前用户未登录或超时或重复登录,token 验证失败，请重新登录
            $this->postApi($params, $item, $url, $token, 1, $method);
        }

        return [
            "status_code" => $status_code,
            "msg" => $msg,
            "data" => $data,
            "return_code" => $return_code,
        ];
    }

    /*
     * post表单数据
     */

    public function post($url, $postContent = [], $header = null, $method = "post") {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //连接前等待时间,0不等待
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //连接后等待时间,0不等待

        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if ($method == "post") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postContent);
        }

        if (strtolower(substr($url, 0, 5)) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }

        $code = 200; //执行成功
        $result_data = curl_exec($ch);
        if (curl_errno($ch)) {

            $code = 400; //执行异常
            $result_data = curl_error($ch);
        }
        curl_close($ch);

        //var_dump($result_data);

        return ['code' => $code, 'data' => $result_data];
    }

    public function getFileToken() {
        $token = "";
        $path = dirname(dirname(dirname(__FILE__))) . "/upfile/baidu/access_token";
        if (!is_dir($path)) {
            mk_dir($path);
        }
        $file = $path . "/" . $this->_apiKey . ".txt";
        if (is_file($file)) {
            if (time() < (filemtime($file) + (60 * 60 * 24 * 25))) { //10分钟失效
                $token = file_get_contents($file);
            }
        }
        return $token;
    }

    public function putFileToken($token) {
        $file = dirname(dirname(dirname(__FILE__))) . '/upfile/baidu/access_token';
        if (!is_file($file)) {
            mk_dir($file);
            file_put_contents($file . "/" . $this->_apiKey . ".txt", $token);
        }
        return true;
    }

}
